package com.fake

import android.widget.RadioGroup
import androidx.fragment.app.Fragment
import com.helloandroid.*
import com.helloandroid.base.BaseActivity
import com.helloandroid.tools.MyLog

class FakeMainActivity : BaseActivity() {

    private lateinit var rgTab: RadioGroup
    private var curKey: String? = null
    override fun getContentViewResId(): Int  = R.layout.activity_fake_main

    override fun initView() {
        rgTab = findViewById(R.id.rgTab)
        rgTab.setOnCheckedChangeListener { _: RadioGroup, _: Int ->
            if (AppUtil.isLogin) {
                updateFragment()
            } else {
                rgTab.check(R.id.rbZouzou)
                AppUtil.toast("请先进行登陆!")
            }
        }
        updateFragment()
    }

    override fun initData() {
    }

    private fun updateFragment() {

        val newKey = when (rgTab.checkedRadioButtonId) {
            R.id.rbZouzou -> MainActivity.keyZou
            R.id.rbZhuanzhuan -> MainActivity.keyZhuan
            else -> MainActivity.keyWode
        }

        if (newKey == curKey) {
            return
        }

        curKey = newKey
        val fragment = createFragment(newKey)
        supportFragmentManager.beginTransaction().replace(R.id.flMain, fragment).commit()
    }

    private fun createFragment(key: String): Fragment {
        MyLog.elog("createFragment called!")
        return when (key) {
            MainActivity.keyZou -> FakeZouFragment()
            MainActivity.keyZhuan -> FakeZhuanFragment()
            MainActivity.keyWode -> FakeWodeFragment()
            else -> throw RuntimeException("unknow fragment key:$key")
        }
    }

    fun swithToZouFragment() {
        rgTab.check(R.id.rbZouzou)
    }

    private fun swithToZhuanFragment() {
        rgTab.check(R.id.rbZhuanzhuan)
    }

    fun swithToWodeFragment() {
        rgTab.check(R.id.rbWode)
    }

    // 上次按 back 按键的时间
    var pressBackTimeMs = 0L
    override fun onBackPressed() {

        when (curKey) {
            MainActivity.keyZou -> {
                if (System.currentTimeMillis() - pressBackTimeMs >= 2000L) {
                    AppUtil.toast("再按一次退出!")
                    pressBackTimeMs = System.currentTimeMillis()
                } else {
                    super.onBackPressed()
                }
            }
            MainActivity.keyZhuan -> {
                swithToZouFragment()
            }
            MainActivity.keyWode -> {
                swithToZouFragment()
            }
            else -> {
                // do nothing...
            }
        }
    }
}